package com.five.filesync;

import android.os.AsyncTask;
import android.util.Log;

import com.five.filesync.bean.UploadRespondBean;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;


import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FileUploaderRequest extends AsyncTask<String, Void, Boolean> {
    private static final String TAG = "FileUploader";

    private String mUrl;
    private String dirname;
    private File mLocalFile;
    private OnNetCallback callback;

    public FileUploaderRequest(InetAddress host, int port, String dirname, File localFile, OnNetCallback callback) {
        this.mUrl = String.format("http://%s:%s/upload", host.getHostAddress(), port);
        this.dirname = dirname;
        this.mLocalFile = localFile;
        this.callback = callback;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        OkHttpClient client = new OkHttpClient();

        // 创建文件
        final File file = mLocalFile;

        // 创建请求体
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .addFormDataPart("dirname", dirname)
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(mUrl)
                .post(requestBody)
                .build();

        // 发送请求
        try {
            Response response = client.newCall(request).execute();

            // 处理响应
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                Gson gson = new Gson();
                UploadRespondBean bean = gson.fromJson(responseBody, UploadRespondBean.class);
                if (bean.getStatus() != 0) {
                    // ok
                    // 文件上传成功
                    Log.d(TAG, String.format("File uploaded successfully! url=%s, localFile=%s, msg=%s", mUrl, mLocalFile.getAbsolutePath(), bean.getMsg()));
                    return true;
                } else {
                    Log.d(TAG, String.format("File uploaded failed! url=%s, localFile=%s, msg=%s", mUrl, mLocalFile.getAbsolutePath(), bean.getErr()));
                }
            } else {
                Log.d(TAG, String.format("File uploaded failed! url=%s, localFile=%s, msg=%s", mUrl, mLocalFile.getAbsolutePath(), ""));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean ret) {
        if (this.callback != null) {
            this.callback.onResult(ret, null);
        }
    }
}